package com.jdy.haoduoaiteacher.fragment;


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.jdy.haoduoaiteacher.Constant;
import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.activity.AddHabitClockActivity;
import com.jdy.haoduoaiteacher.activity.BaseActivity;
import com.jdy.haoduoaiteacher.activity.PersonalInformationActivity2;
import com.jdy.haoduoaiteacher.adapter.RecentPlayAdapter;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.model.HabitNumItem;
import com.jdy.haoduoaiteacher.model.HabitPlan;
import com.jdy.haoduoaiteacher.model.LeHabitPlanRecordWrapper;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.model.XxbClassInfo;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.ImageUtils;
import com.jdy.haoduoaiteacher.util.OnDataReceivedListener;
import com.jdy.haoduoaiteacher.util.PathUtil;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.jdy.haoduoaiteacher.view.RefreshableView;
import com.jdy.haoduoaiteacher.view.RefreshableView.RefreshListener;
import com.jdy.haoduoaiteacher.view.calendar.adpter.WeekCalendarAdpter.OnDateSelectListener;
import com.jdy.haoduoaiteacher.view.calendar.fragment.MyCalendarFragment;
import com.jdy.haoduoaiteacher.view.scrollview.ObservableScrollView;
import com.jdy.haoduoaiteacher.view.scrollview.OnScrollChangedCallback;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.adapter.CommonAdapter;
import com.ycsj.goldmedalnewconcept.adapter.ViewHolder;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.UiHelper;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import se.emilsjolander.stickylistheaders.StickyListHeadersListView;

import static android.view.View.GONE;

/**
 * @author hf
 */
@SuppressLint({"InflateParams", "HandlerLeak"})
public class TabIndexFragment extends BaseFragment implements
        OnScrollListener, OnClickListener,
        OnCompletionListener, RefreshListener, /*OnSetAlarmListener,*/
        OnDateSelectListener, OnDataReceivedListener,
        OnScrollChangedCallback, StickyListHeadersListView.OnHeaderClickListener,
        StickyListHeadersListView.OnStickyHeaderOffsetChangedListener,
        StickyListHeadersListView.OnStickyHeaderChangedListener {

    private static final String TAG = TabIndexFragment.class.getSimpleName();


    @InjectView(id = R.id.outside)
    private LinearLayout llOut;
    @InjectView(id = R.id.scroll_view)
    private ObservableScrollView scroll_view;
    @InjectView(id = R.id.tv_selectdate)
    private TextView tv_selectdate;
    @InjectView(id = R.id.tv_class)
    private TextView tv_class;
    //    @InjectView(id = R.id.headicon, click = true)
    private ImageView headicon;

    @InjectView(id = R.id.tv_recustom, click = true)
    private TextView tv_recustom;
    @InjectView(id = R.id.view_hh)
    private View view_hh;
    private LinearLayout linearLayout2;
    @InjectView(id = R.id.content_views, click = true)
    private StickyListHeadersListView listview;

    //弹框相关
    private View popView;
    private PopupWindow popupWindow;
    private ListView lv;
    private ClassAdapter classAdapter;
    //控制PopUpWindow的显示与关闭
    private boolean isShowing;

    private boolean isPageChanged;

    private LeUser mLeUser;

    private BaseActivity mBaseActivity;

    //日历控件的Fragment
    private MyCalendarFragment myCalenderFragment;

    private Bitmap mScaleCrop;

    private BroadcastReceiver mReceiver = null;

    //班级信息
    private List<ClassInfo> classInfos;

    //适配器对象
    private RecentPlayAdapter adapter;

    //创建班级信息的对象
    private ClassInfo classInfo;

    //适配器的的数据集合
    private ArrayList<LeHabitPlanRecordWrapper> mList;

    public static ArrayList<HabitNumItem> mListHabitNumItem = new ArrayList<>();

    private ImageView add_no_class;

    private String mCustomDate;

    private String mCurDay;

    private String selectQueryDate;

    private String classNum;

    private boolean fadeHeader = true;

    @SuppressLint("ValidFragment")
    public TabIndexFragment(BaseActivity ba) {
        mBaseActivity = ba;
    }

    public TabIndexFragment() {
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    @SuppressWarnings("deprecation")
    @SuppressLint({"ClickableViewAccessibility", "SimpleDateFormat"})
    @Override
    public View onCreateView(Bundle savedInstanceState, LayoutInflater inflater,
                             ViewGroup container) {

        View bodyView = LayoutInflater.from(mContext).inflate(
                R.layout.activity_calendar_teacher, container, false);

        View plistview = bodyView.findViewById(R.id.plistview);
        add_no_class = bodyView.findViewById(R.id.add_no_class);


        headicon = bodyView.findViewById(R.id.headicon);
        String icon = SPUtil.getString(getActivity(), "icon", "");

        if (!TextUtils.isEmpty(icon)) {
            Picasso.with(getActivity()).load(icon).into(headicon);
        }

        headicon.setOnClickListener(this);
        add_no_class.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), AddHabitClockActivity.class);
                intent.putExtra("selectQueryDate", selectQueryDate);
                intent.putExtra("classnum", classNum);
                startActivity(intent);
            }
        });

        //获取班级信息
        getClassData();

        listview = plistview.findViewById(R.id.content_views);

        linearLayout2 = bodyView.findViewById(R.id.linearLayout2);

        linearLayout2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                //点击选择班级弹出下拉框的操作

                if (null == classInfos || classInfos.size() == 0) {

                    //证明没有班级信息
                    UiHelper.toast(getActivity(), "暂无班级信息");

                    return;

                } else {
                    showChooseClassPopAction();
                }
            }
        });

        return bodyView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //设置默认班级信息
        if (null != classInfos && classInfos.size() != 0) {
            //默认取第一个班级进行显示
            tv_class.setText(classInfos.get(0).className);
        }

        mList = new ArrayList<>();

        //初始化方法
        init();

        Log.i("test", "当前的mCurDay是:" + mCurDay);

        //根据当前的月份初始化数据
        if (Tools.isNotEmpty(mCurDay)) {
            loadDataByMonth(mCurDay.substring(0, 7));
        }

        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if ("updatebabyheadimage".equals(action)) {
                    SharedPreferences prefs = mContext.getSharedPreferences(
                            Constant.USER_INFO, Context.MODE_PRIVATE);

                    String parentImagePath = prefs.getString(Constant.BABY_AVATAR, "");
                    if (Tools.isNotEmpty(parentImagePath)) {
                        Uri parentUri = Uri.parse(parentImagePath);

                        Bitmap originalBitmap = ImageUtils.getBitmapFromUri(mContext,
                                parentUri);
                        if (originalBitmap != null) {
                            mScaleCrop = ImageUtils.scaleCropToFit(originalBitmap, 300, 300,
                                    true);
                        }
                    }
                } else if ("bindNewDeviceSuccess".equals(action)) {

                } else if ("updatehabit".equals(action)
                        //接受到更新的广播了
                        && Tools.isNotEmpty(selectQueryDate)) {
                    loadDataByMonth(selectQueryDate.substring(0, 7));
                }
            }
        };

        //注册广播接受者
        IntentFilter filter = new IntentFilter();
        filter.addAction("updatehabit");
        filter.addAction("updatebabyheadimage");
        filter.addAction("bindNewDeviceSuccess");
        mContext.registerReceiver(mReceiver, filter);
    }


    /**
     * 设置用户头像
     */
    private void setUserAvatar() {
        SharedPreferences prefs = mContext.getSharedPreferences(Constant.USER_INFO,
                Context.MODE_PRIVATE);
        String parentImagePath = prefs.getString(Constant.PARENT_AVATAR, "");
        if (Tools.isNotEmpty(parentImagePath)) {
            Uri parentUri = Uri.parse(parentImagePath);

            if (mScaleCrop == null) {
                Bitmap originalBitmap = ImageUtils
                        .getBitmapFromUri(mContext, parentUri);
                if (originalBitmap != null) {
                    mScaleCrop = ImageUtils
                            .scaleCropToFit(originalBitmap, 300, 300, true);
                }
            }
        } else if (Tools.isEmpty(parentImagePath) && mLeUser != null) {
            getHeadImage(mLeUser.member_types.get(0).avatar);
        }
    }

    /**
     * 获取头像的方法
     * 先从Sp取头像信息,如果Sp中没有,在从服务器获取
     *
     * @param remoteHeadImageFilePath
     */
    private void getHeadImage(String remoteHeadImageFilePath) {
        if (Tools.isNullStr(remoteHeadImageFilePath)) {
            return;
        }

        SharedPreferences prefs = mContext.getSharedPreferences(Constant.USER_INFO,
                Context.MODE_PRIVATE);

        String babyImagePath = prefs.getString(Constant.PARENT_AVATAR, "");

        if (Tools.isNullStr(babyImagePath)) {
            new AsyncTask<String, Void, Bitmap>() {
                @Override
                protected void onPostExecute(Bitmap result) {
                    if (result != null) {
                        String path = PathUtil.getBabyAvatarPath(mContext
                                .getApplicationContext());
                        FileOutputStream out = null;
                        File babyAvatarFile = new File(path);
                        try {
                            out = new FileOutputStream(babyAvatarFile);
                            result.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is
                            SharedPreferences prefs = mContext.getSharedPreferences(
                                    Constant.USER_INFO, Context.MODE_PRIVATE);
                            Uri babyAvatarUri = Uri.fromFile(babyAvatarFile);
                            prefs.edit()
                                    .putString(Constant.PARENT_AVATAR, babyAvatarUri.toString())
                                    .apply();
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                if (out != null) {
                                    out.close();
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }

                @Override
                protected Bitmap doInBackground(String... urls) {
                    String urldisplay = urls[0];

                    Bitmap resultImage = null;

                    URL url;
                    try {
                        url = new URL(urldisplay);

                        HttpURLConnection urlConnection = (HttpURLConnection) url
                                .openConnection();

                        urlConnection.setRequestMethod("GET");

                        urlConnection.connect();

                        InputStream in = urlConnection.getInputStream();

                        resultImage = BitmapFactory.decodeStream(in);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return resultImage;
                }
            }.execute(remoteHeadImageFilePath);
        }
    }


    /**
     * 核心方法,请求服务器获取班级的信息
     * 通过月份获取数据的方法
     *
     * @param strDate
     */
    private void loadDataByMonth(final String strDate) {
        new CustomAsyncTask(getActivity(), new IAsyncTask() {

            @Override
            public ResponseResult doInbackground(Activity activity) {
                if (mLeUser == null) {
                    mLeUser = Tools.restoreLeUser();
                }
                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                param_.put("date", strDate);
                param_.put("class_num", classNum);
                Log.i("test", HttpUtils.API_URL + "/api/2.0/operation/habit/habits_teacher?" +
                        HttpUtils.TAG_SNO_I + "=" + mLeUser.sno + "&" + HttpUtils.TAG_KEY_I + "=" + HttpUtils.KEY + "&date=" +
                        strDate + "&class_num=" + classNum);
                return HttpUtils.startRequest(
                        HttpUtils.API_URL + "/api/2.0/operation/habit/habits_teacher", param_,
                        HttpUtils.TAG_GET_REQUEST);
            }

            @SuppressLint("SimpleDateFormat")
            @Override
            public void onRecieveData(Activity activity, ResponseResult arg0) {
                if (arg0.isSuccess()) {
                    Log.i("test", "获取到的主页数据是:" + arg0.data);
                    if (Tools.isNotNullStr(arg0.data)) {
                        if (Tools.isNotEmpty(arg0) && Tools.isNotEmpty(arg0.data)) {

                            mList.clear();
                            mListHabitNumItem.clear();
                            try {
                                JSONObject result = new JSONObject(arg0.data);
                                Iterator<?> it = result.keys();
                                String keyDate = null;
                                while (it.hasNext()) {// 遍历JSONObject
                                    keyDate = it.next().toString();

                                    if (Tools.isNotEmpty(keyDate)) {
                                        JSONArray playList = result.getJSONArray(keyDate);
                                        // 获取JSONArray
                                        if (Tools.isNotEmpty(playList)) {
                                            ArrayList<HabitPlan> list = (ArrayList<HabitPlan>) JsonSerializer
                                                    .getInstance().deserialize(playList.toString(),
                                                            ArrayList.class, HabitPlan.class);
                                            if (Tools.isNotEmpty(list)) {
                                                LeHabitPlanRecordWrapper itemVo = new LeHabitPlanRecordWrapper();
                                                itemVo.dateTag = keyDate;
                                                itemVo.list = list;
                                                mList.add(itemVo);
                                                HabitNumItem item = new HabitNumItem();
                                                item.dateStr = keyDate;
                                                item.num = list.size();
                                                mListHabitNumItem.add(item);
                                            }
                                        }
                                    }
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            if (getActivity() != null) {


                                //主线程更新UI
                                getActivity().runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        //设置适配器
                                        setAdapter();

                                        myCalenderFragment.setDataList(mListHabitNumItem);
                                    }
                                });
                            }
                        }
                    }
                }

                isPageChanged = false;
            }

        }).execute();
    }

    /**
     * 设置适配器的方法
     */
    private void setAdapter() {
        if (adapter == null) {
            adapter = new RecentPlayAdapter(mBaseActivity, mList);
            listview.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        } else {
            adapter.setData(mList);
            adapter.notifyDataSetChanged();
        }

        if (mList.isEmpty()) {
            add_no_class.setVisibility(View.VISIBLE);
        } else {
            add_no_class.setVisibility(GONE);
        }

        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).dateTag.contains(selectQueryDate)) {
                listview.smoothScrollToPosition(i);
                final int j = i;
                adapter.setHighLightPosition(j);
                listview.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        listview.setSelection(j);


                    }
                }, 500);

                break;
            }
        }

    }

    /**
     * 获取班级信息的方法
     */
    private void getClassData() {

        //设置班级数据
        classInfos = new ArrayList<>();

        //从Sp中取出班级的信息
        String classJson = SPUtil.getString(getActivity(), "classjson", "");
        if (!TextUtils.isEmpty(classJson)) {
            //解析JSON获取班级信息
            Log.i("test", "获取到的json是:" + classJson);
            parseJson(classJson);
        } else {
            Log.i("test", "无班级信息");
        }

        //给请求服务器需要上传的clssNum赋初值
        if (classInfos.size() != 0) {
            classNum = classInfos.get(0).classNum;
            SPUtil.putString(getActivity(), "classnumxxj", classNum);
            SPUtil.putString(getActivity(), "classnamexxj", classInfos.get(0).className);
        }
    }


    /**
     * 解析服务器返回的json获取班级信息
     *
     * @param classJson
     */
    private void parseJson(String classJson) {
        try {
            XxbClassInfo info = GsonUtil.jsonToBean(classJson, XxbClassInfo.class);

            if (info.classinfo0 != null && !TextUtils.isEmpty(info.classinfo0.name)) {
                classInfo = new ClassInfo(info.classinfo0.name);
                classInfo.isSelect = true;
                classInfo.classNum = info.classinfo0.num;
                classInfos.add(classInfo);
            }
            if (info.classinfo1 != null && !TextUtils.isEmpty(info.classinfo1.name)) {
                classInfo = new ClassInfo(info.classinfo1.name);
                classInfo.classNum = info.classinfo1.num;
                classInfos.add(classInfo);
            }

            if (info.classinfo2 != null && !TextUtils.isEmpty(info.classinfo2.name)) {
                classInfo = new ClassInfo(info.classinfo2.name);
                classInfo.classNum = info.classinfo2.num;
                classInfos.add(classInfo);
            }

            if (info.classinfo3 != null && !TextUtils.isEmpty(info.classinfo3.name)) {
                classInfo = new ClassInfo(info.classinfo3.name);
                classInfo.classNum = info.classinfo3.num;
                classInfos.add(classInfo);
            }

            if (info.classinfo4 != null && !TextUtils.isEmpty(info.classinfo4.name)) {
                classInfo = new ClassInfo(info.classinfo4.name);
                classInfo.classNum = info.classinfo4.num;
                classInfos.add(classInfo);
            }

            if (info.classinfo5 != null && !TextUtils.isEmpty(info.classinfo5.name)) {
                classInfo = new ClassInfo(info.classinfo5.name);
                classInfo.classNum = info.classinfo5.num;
                classInfos.add(classInfo);
            }

            if (info.classinfo6 != null && !TextUtils.isEmpty(info.classinfo6.name)) {
                classInfo = new ClassInfo(info.classinfo6.name);
                classInfo.classNum = info.classinfo6.num;
                classInfos.add(classInfo);
            }

            if (info.classinfo7 != null && !TextUtils.isEmpty(info.classinfo7.name)) {
                classInfo = new ClassInfo(info.classinfo7.name);
                classInfo.classNum = info.classinfo7.num;
                classInfos.add(classInfo);
            }

            if (info.classinfo8 != null && !TextUtils.isEmpty(info.classinfo8.name)) {
                classInfo = new ClassInfo(info.classinfo8.name);
                classInfo.classNum = info.classinfo8.num;
                classInfos.add(classInfo);
            }

            if (info.classinfo9 != null && !TextUtils.isEmpty(info.classinfo9.name)) {
                classInfo = new ClassInfo(info.classinfo9.name);
                classInfo.classNum = info.classinfo9.num;
                classInfos.add(classInfo);
            }

        } catch (Exception e) {
            e.printStackTrace();
            Log.i("test", "数据解析异常");
        }
    }

    /**
     * 初始化的方法,配置日历控件为默认的今天的日期
     */
    private void init() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        mCurDay = sdf.format(Calendar.getInstance().getTime());

        selectQueryDate = mCurDay;

        listview.setOnHeaderClickListener(this);
        listview.setOnStickyHeaderChangedListener(this);
        listview.setOnStickyHeaderOffsetChangedListener(this);
        listview.setDrawingListUnderStickyHeader(true);
        listview.setAreHeadersSticky(true);

        myCalenderFragment = new MyCalendarFragment(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
            }
        }, false, mListHabitNumItem);

        myCalenderFragment.setOnDateSelectListener(this);
        //将日历控件添加到
        ((BaseActivity) mContext).getSupportFragmentManager().beginTransaction()
                .add(R.id.re_cotent, myCalenderFragment).show(myCalenderFragment)
                .commit();

        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                myCalenderFragment.switch2MonthView();

                String year = myCalenderFragment.getMonthViewDateStr().substring(0, 4);
                String month = myCalenderFragment.getMonthViewDateStr().substring(5, 7);
                tv_selectdate.setText(year + "年 " + month + "月");
                view_hh.setVisibility(View.VISIBLE);
            }
        }, 500);

        //设置用户头像
        setUserAvatar();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }

        try {
            if (mContext != null && mReceiver != null) {
                mContext.unregisterReceiver(mReceiver);
                mReceiver = null;
            }
        } catch (Exception e) {
        }
    }

    /**
     * 对用户可见的时候设置数据
     *
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isVisibleToUser) {
            if (popupWindow != null && popupWindow.isShowing()) {
                popupWindow.dismiss();
                isShowing = false;
            }
        }
    }


    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.headicon:
                intent.setClass(getActivity(), PersonalInformationActivity2.class);
                startActivity(intent);
                break;
            case R.id.tv_recustom:
                // 添加习惯
                intent.setClass(getActivity(), AddHabitClockActivity.class);
                intent.putExtra("selectQueryDate", selectQueryDate);
                intent.putExtra("classnum", classNum);
                startActivity(intent);
                break;
        }
    }


    /**
     * 弹出选择班级下拉框的操作
     */
    private void showChooseClassPopAction() {

        if (popView == null) {
            popView = View.inflate(getActivity(), R.layout.item_pop_class, null);
        }
        lv = popView.findViewById(R.id.lv);

        classAdapter = new ClassAdapter(getActivity(), classInfos, R.layout.item_lv_class);

        lv.setAdapter(classAdapter);

        //设置点击事件
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                //回显值
                tv_class.setText(classInfos.get(pos).className);
                classAdapter.upDatePos(pos);
                popupWindow.dismiss();
                isShowing = false;
                classNum = classInfos.get(pos).classNum;
                //重新请求服务器数据刷新页面
                loadDataByMonth(selectQueryDate.substring(0, 7));


                SPUtil.putString(getActivity(), "classnumxxj", classInfos.get(pos).classNum);
                SPUtil.putString(getActivity(), "classnamexxj", classInfos.get(pos).className);
            }
        });

        if (popupWindow == null) {
            popupWindow = new PopupWindow(popView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        }
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                popupWindow = null;
                popView = null;
            }
        });
        //设置进出场动画
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);

        //设置显示位置
        popupWindow.showAsDropDown(linearLayout2);
    }

    @Override
    public void onCompletion(MediaPlayer mp) {

    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    @Override
    public void onScroll(int l, int t, int oldl, int oldt) {

    }

    @Override
    public void onDataReceived(String data) {

    }

    @Override
    public void onDateSelected(String dateStr) {

        selectQueryDate = dateStr;

        if (Tools.isNotEmpty(dateStr)) {
            tv_selectdate.setText(dateStr.subSequence(0, 4) + "年 "
                    + dateStr.substring(5, 7) + "月");
        }

        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).dateTag.contains(selectQueryDate)) {
                listview.smoothScrollToPosition(i);
                final int j = i;
                adapter.setHighLightPosition(j);
                listview.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        listview.setSelection(j);

                    }
                }, 500);
                break;
            }
        }
    }


    @Override
    public void changeDate(String date, String viewType) {
        if (Tools.isEmpty(date)) {
            return;
        }

        String year = date.substring(0, 4);
        String month = date.substring(5, 7);

        String firstDayThisMonth = null, endDayThisMonth = null;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date dateee;
        try {
            dateee = sdf.parse(date);
            Calendar cal = Calendar.getInstance();
            cal.setTime(dateee);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            cal.getTime();
            firstDayThisMonth = sdf.format(cal.getTime()) + "";

            cal = Calendar.getInstance();
            cal.setTime(dateee);
            cal.set(Calendar.DAY_OF_MONTH,
                    cal.getActualMaximum(Calendar.DAY_OF_MONTH));
            cal.getTime();
            endDayThisMonth = sdf.format(cal.getTime()) + "";
        } catch (ParseException e) {
            e.printStackTrace();
        }

        tv_selectdate.setText(year + "年 " + month + "月");

        isPageChanged = true;
        mCustomDate = date;

        LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
        if (lu == null) {
            lu = Tools.restoreLeUser();
        }

        if (isPageChanged) {
            String dateString = date;

            if (!dateString.contains(mCurDay)) {
                dateString = dateString.substring(0, 7) + "-01";
            }

            String queryDateStr = mCustomDate;

            {
                if (myCalenderFragment.getSelectTime().compareTo(endDayThisMonth) <= 0
                        && myCalenderFragment.getSelectTime().compareTo(firstDayThisMonth) >= 0) {
                    queryDateStr = myCalenderFragment.getSelectTime();
                } else {
                    queryDateStr = firstDayThisMonth;
                }

                loadDataByMonth(queryDateStr.substring(0, 7));
                selectQueryDate = queryDateStr;
            }

        }
    }

    @Override
    public void onRefresh(RefreshableView view) {

    }


    @Override
    public void onHeaderClick(StickyListHeadersListView l, View header,
                              int itemPosition, long headerId, boolean currentlySticky) {
    }

    @Override
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void onStickyHeaderOffsetChanged(StickyListHeadersListView l,
                                            View header, int offset) {
        if (fadeHeader && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            header.setAlpha(1 - (offset / (float) header.getMeasuredHeight()));
        }
    }

    @Override
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void onStickyHeaderChanged(StickyListHeadersListView l, View header,
                                      int itemPosition, long headerId) {
        header.setAlpha(1);

        header.setBackgroundColor(0xffffffff);
    }


    /**
     * 显示班级弹框的列表适配器
     */
    class ClassAdapter extends CommonAdapter<ClassInfo> {

        private List<ClassInfo> datas;

        public ClassAdapter(Context context, List<ClassInfo> datas, int layoutId) {
            super(context, datas, layoutId);
            this.datas = datas;
        }

        @Override
        public void convert(ViewHolder holder, ClassInfo info) {
            TextView tv = holder.getView(R.id.tv);
            tv.setText(info.className);

            //右边选中状态
            ImageView lv = holder.getView(R.id.lv);
            if (info.isSelect) {
                lv.setVisibility(View.VISIBLE);
            } else {
                lv.setVisibility(View.GONE);
            }
        }

        /**
         * 点击条目后选中条目的方法
         *
         * @param pos
         */
        public void upDatePos(int pos) {
            for (int i = 0; i < datas.size(); i++) {
                if (pos == i) {
                    datas.get(pos).isSelect = true;
                } else {
                    datas.get(i).isSelect = false;
                }
            }
            notifyDataSetChanged();
        }
    }

    /**
     * 控制班级的显示类
     */
    class ClassInfo {

        public ClassInfo(String className) {
            this.className = className;
        }

        public String className;
        public boolean isSelect;
        public String classNum;
    }
}
